package com.bridgeintelligent.tag.combination.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bridgeintelligent.tag.combination.entity.CombinationCodes;
import com.bridgeintelligent.tag.combination.entity.CombinationPage;
import com.bridgeintelligent.tag.combination.entity.Result;
import com.bridgeintelligent.tag.combination.exception.CombinationException;
import com.bridgeintelligent.tag.combination.mapper.CombinationMapper;
import com.bridgeintelligent.tag.combination.mapper.CombinationQueryModelMapper;
import com.bridgeintelligent.tag.combination.pojo.*;
import com.bridgeintelligent.tag.constants.DimCofig;
import com.bridgeintelligent.tag.constants.ExceptionCodes;
import com.bridgeintelligent.tag.constants.TagConstants;
import com.bridgeintelligent.tag.mapper.DimItemMapper;
import com.bridgeintelligent.tag.mapper.DimMapper;
import com.bridgeintelligent.tag.user.mgmt.pojo.User;
import com.bridgeintelligent.tag.utils.DateHelper;
import com.bridgeintelligent.tag.utils.FieldHandler;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.DimCatalog;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.DimData;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.DimItem;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.IdWorker;
import com.bridgeintelligent.tag.webserver.dim.mgmt.service.es.IEsInfoService;
import com.bridgeintelligent.tag.webserver.security.TagSecurityHelper;
import com.bridgeintelligent.tag.webserver.workflow.repository.InstanceMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wayneleo.quickstart.framework.IDGenerator;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 客群服务层接口实现
 */

@Service
@Transactional
@AllArgsConstructor
public class CombinationServiceImpl implements CombinationService {

    private CombinationMapper combinationMapper;

    private CombinationQueryModelMapper queryModelMapper;

    private DimMapper dimMapper;

    private DimItemMapper dimItemMapper;
    //组合标签英文名前缀
    private static final String PREFIX = "composite_tag";

    private InstanceMapper instanceMapper;

    private IEsInfoService esInfoService;


    /**
     * 校验组合标签名是否重复
     *
     * @param combinationName
     * @return
     */
    @Override
    public boolean checkCombinationName(String combinationName) {
        int count = combinationMapper.checkCombinationName(combinationName);
        if (count == 1) {
            return false;
        }
        return true;
    }

    @Override
    public void addCombination(String combinationName,  String defaultCode,String combinationDes, String scenarious, String departId, JSONArray jsonArrays,String defaultName,String renew,String rule,String manager) {
        addCombination(combinationName,defaultCode,combinationDes, scenarious,departId,jsonArrays,defaultName,renew,manager,null);
    }

    @Override
    public void addCombination(String combinationName,  String defaultCode,String combinationDes, String scenarious, String departId,
                               JSONArray jsonArrays,String defaultName,String renew,String rule,String manager,
                               String businessType) {

        Combination combination = new Combination();
        //设置id
        combination.setCombinationId(PREFIX+getMaxIndex());//保持dimId和colName一致性
        combination.setSortNum(getMaxSortNum());//当前最大标签序号
        combination.setColName(combination.getCombinationId());
        combination.setMaxIndex(getMaxIndex());
        combination.setCombinationName(combinationName);
        combination.setCombinationDes(combinationDes);
        combination.setBusinessType(businessType);
        combination.setScenarious(scenarious);
        combination.setDepartId(departId);
        combination.setRenew(renew);
        combination.setRule(rule);
        combination.setManager(manager);
        combination.setClassify("02");
        combination.setPath("私有标签");
        combination.setCommended(false);
        //默认审批状态
        combination.setApprovalStatus("1");
        User user = TagSecurityHelper.currentUser();
        //负责人
        combination.setOwnerName(user.getName());
        combination.setOwnerId(user.getUserId());
        //创建时间,更新时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        combination.setCreateTime(sdf.format(new Date()));
        combination.setUptTime(sdf.format(new Date()));

        CombinationGroup defGroup = new CombinationGroup();//设置默认结果
        defGroup.setId(IDGenerator.gen());
        defGroup.setCombinationId(combination.getCombinationId());
        defGroup.setGroupNum("0");
        defGroup.setLabitemCode(defaultCode);
        defGroup.setLabitemName(defaultName);
        queryModelMapper.addQueryGroup(defGroup);

        for (int i = 0; i < jsonArrays.size() ; i++) {

            JSONObject jsonObject = jsonArrays.getJSONObject(i);
            //保存查询条件
            QueryModel queryModel = JSON.toJavaObject(jsonObject, QueryModel.class);

            CombinationGroup cgroup = new CombinationGroup();
            cgroup.setId(IDGenerator.gen());
            cgroup.setCombinationId(combination.getCombinationId());
            cgroup.setGroupNum(queryModel.getGroupNum());
            cgroup.setLabitemCode(queryModel.getLabitemCode());
            cgroup.setLabitemName(queryModel.getLabitemName());
            queryModelMapper.addQueryGroup(cgroup);

            if (queryModel.getFilterGroup() == null) {
                throw new CombinationException(ExceptionCodes.COMBINATION_80003);
            }
            //新增条件组
            String parentId = "-";
            setFilterGroup(combination.getCombinationId(),queryModel.getGroupNum(), queryModel.getFilterGroup(), parentId);
        }
        //新增组合标签
        combinationMapper.addCombination(combination);
        //保存sql数据
        saveCombinationData(combination.getCombinationId());
    }

    @Override
    public void addCombination(CombinationModel combinationModel) {
        Combination combination = new Combination();
        final JSONArray jsonArrays = JSONObject.parseArray(combinationModel.getQueryCriteria());
        //设置id
        combination.setCombinationId(PREFIX+getMaxIndex());//保持dimId和colName一致性
        combination.setSortNum(getMaxSortNum());//当前最大标签序号
        combination.setColName(combination.getCombinationId());
        combination.setMaxIndex(getMaxIndex());
        combination.setCombinationName(combinationModel.getCombinationName());
        combination.setCombinationDes(combinationModel.getCombinationDes());
        combination.setBusinessType(combinationModel.getBusinessType());
        combination.setScenarious(combinationModel.getScenarious());
        combination.setDepartId(combinationModel.getDepartId());
        combination.setRenew(combinationModel.getRenew());
        combination.setRule(combinationModel.getRule());
        combination.setManager(combinationModel.getManager());
        combination.setValidTime(combinationModel.getValidTime());
        combination.setClassify("02");
        combination.setPath("私有标签");
        combination.setCommended(false);
        //默认审批状态
        combination.setApprovalStatus("1");
        User user = TagSecurityHelper.currentUser();
        //负责人
        combination.setOwnerName(user.getName());
        combination.setOwnerId(user.getUserId());
        //创建时间,更新时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        combination.setCreateTime(sdf.format(new Date()));
        combination.setUptTime(sdf.format(new Date()));

        CombinationGroup defGroup = new CombinationGroup();//设置默认结果
        defGroup.setId(IDGenerator.gen());
        defGroup.setCombinationId(combination.getCombinationId());
        defGroup.setGroupNum("0");
        defGroup.setLabitemCode(combinationModel.getDefaultCode());
        defGroup.setLabitemName(combinationModel.getDefaultName());
        queryModelMapper.addQueryGroup(defGroup);

        for (int i = 0; i < jsonArrays.size() ; i++) {

            JSONObject jsonObject = jsonArrays.getJSONObject(i);
            //保存查询条件
            QueryModel queryModel = JSON.toJavaObject(jsonObject, QueryModel.class);

            CombinationGroup cgroup = new CombinationGroup();
            cgroup.setId(IDGenerator.gen());
            cgroup.setCombinationId(combination.getCombinationId());
            cgroup.setGroupNum(queryModel.getGroupNum());
            cgroup.setLabitemCode(queryModel.getLabitemCode());
            cgroup.setLabitemName(queryModel.getLabitemName());
            queryModelMapper.addQueryGroup(cgroup);

            if (queryModel.getFilterGroup() == null) {
                throw new CombinationException(ExceptionCodes.COMBINATION_80003);
            }
            //新增条件组
            String parentId = "-";
            setFilterGroup(combination.getCombinationId(),queryModel.getGroupNum(), queryModel.getFilterGroup(), parentId);
        }
        //新增组合标签
        combinationMapper.addCombination(combination);
        //保存sql数据
        saveCombinationData(combination.getCombinationId());
    }

    private int getMaxIndex(){
        int maxIndex = 1;
        Integer index = combinationMapper.findMaxIndex();
        if (index != null){
            maxIndex = index+1;
        }
        return maxIndex;
    }


    /**
     * 查询当前最大标签序号
     * @return
     */
    private int getMaxSortNum(){
        int maxSort = 50001;
        Integer sortNum = combinationMapper.findMaxSortNum();
        if (null != sortNum && sortNum >0){
            maxSort = sortNum+1;
        }
        return maxSort;
    }

    /**
     * 根据组合标签id查找组合标签名称
     *
     * @param combiantionId
     * @return
     */
    @Override
    public String findCombinationNameById(String combiantionId) {

        return combinationMapper.findCombinationNameById(combiantionId);
    }

    /**
     * 分页条件查询组合标签列表
     *
     * @param pageNumber
     * @param pageSize
     * @param combinationName
     * @return
     */
    @Override
    public Result list(Integer pageNumber, Integer pageSize, String combinationName, String status, String uptTimeStart, String uptTimeEnd) {
        //获取当前用户的id
        User user = TagSecurityHelper.currentUser();
        Map map = new HashMap();
        map.put("userId", user.getUserId());
        map.put("combinationName", combinationName);
        map.put("status", status);
        map.put("uptTimeStart", uptTimeStart);
        if (uptTimeEnd != null && !"".equals(uptTimeEnd)) {
            map.put("uptTimeEnd", uptTimeEnd + "23.59.59");
        }
        String dataTime = esInfoService.dataTime();
        map.put("dataTime",dataTime);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(calendar.MONTH, -1);
        String temp = format(calendar.getTime());

        Page page = PageHelper.startPage(pageNumber, pageSize);

        List<Combination> list = new ArrayList<>();
        if (FieldHandler.isUnionAdmin(user.getRoleId())){
            //如果是超管
            list = combinationMapper.findUnionAdminList(map);
        }else{
            list = combinationMapper.findList(map);
        }

        if (list != null && !list.isEmpty()) {
            for (Combination combination : list) {
                if ("1".equals(combination.getApprovalStatus())) {
                    combination.setStatusName("未提交");
                } else if ("2".equals(combination.getApprovalStatus())) {
                    combination.setApprovalStatusName("待审核");
                } else if ("3".equals(combination.getApprovalStatus())) {
                    combination.setApprovalStatusName("驳回");
                } else if ("4".equals(combination.getApprovalStatus())) {
                    combination.setApprovalStatusName("已通过");
                }
                if (temp.compareTo(combination.getUptTime()) < 1) {
                    combination.setIsnew(true);
                } else {
                    combination.setIsnew(false);
                }
            }
        }
        CombinationPage<Combination> combinationPage = new CombinationPage<>();
        combinationPage.setContent(list);
        combinationPage.setTotalPages(page.getPages());
        combinationPage.setTotalElements(page.getTotal());
        combinationPage.setSize(page.getPageSize());
        combinationPage.setRequestPager(pageNumber);
        return new Result(CombinationCodes.SUCCESS, combinationPage);
    }

    //新增条件组
    private void setFilterGroup(String combinationId, String groupNum, FilterGroup children, String parentId) {

        FilterGroup filterGroupSet = new FilterGroup();
        filterGroupSet.setId(IDGenerator.gen());
        filterGroupSet.setSymbol(children.getSymbol());
        filterGroupSet.setParentId(parentId);
        filterGroupSet.setCombinationId(combinationId);
        filterGroupSet.setGroupNum(groupNum);
        filterGroupSet.setLocation(children.getLocation());
        //存到filterGroup表
        queryModelMapper.addFilterGroup(filterGroupSet);

        //filter
        Filter filterSet;
        if (children.getFilters() != null && !children.getFilters().isEmpty()) {
            for (Filter filter : children.getFilters()) {

                filterSet = new Filter();
                filterSet.setId(IDGenerator.gen());
                filterSet.setDimId(filter.getDimId());
                filterSet.setDimName(filter.getDimName());
                filterSet.setValueListStr(JSON.toJSONString(filter.getValueList()));
                filterSet.setType(filter.getType());
                filterSet.setClassify(filter.getClassify());
                filterSet.setDimLargeType(filter.getDimLargeType());
                filterSet.setTimeType(filter.getTimeType());
                filterSet.setDataDate(filter.getDataDate());
                filterSet.setColName(filter.getDimId());
                filterSet.setCombinationId(combinationId);
                //存入filter
                queryModelMapper.addFilter(filterSet);

                //设置与filterGroup关系
                Map<String, String> map = new HashMap<>();
                map.put("filter_id", filterSet.getId());
                map.put("filtergroup_id", filterGroupSet.getId());
                map.put("combination_id",combinationId);
                String id = IDGenerator.gen();
                map.put("id", id);
                //存入条件组和过滤条件关联关系
                queryModelMapper.addFilterAndFilterGroup(map);
            }
        }
        if (children.getChildren() != null && !children.getChildren().isEmpty()) {
            for (FilterGroup child : children.getChildren()) {
                setFilterGroup(combinationId, groupNum, child, filterGroupSet.getId());
            }
        }
    }

    /**
     * 删除组合标签
     * @param combinationId
     */
    @Override
    public void delCombination(String combinationId) {
        //删除组合标签
        combinationMapper.delUpt(combinationId);
        //将基础标签里的state状态改为03
        combinationMapper.updateStateByDimId(combinationId);
    }

    //删除查询条件
    private void delQueryModel(String combinationId) {

        //通过combinationId查询filtergroup
        List<String> filtergroupIds = queryModelMapper.findFilterGroupBycombinationId(combinationId);

        //通过filtergroupIds查询filterIds
        if (filtergroupIds != null && !filtergroupIds.isEmpty()) {
            for (String filtergroupId : filtergroupIds) {
                List<String> filterIds = queryModelMapper.findFilterIds(filtergroupId);
                //根据filterIds删除filter
                if (filterIds != null && !filterIds.isEmpty()) {
                    for (String filterId : filterIds) {
                        queryModelMapper.delFilterById(filterId);
                        //删除filtergroup与filter的关联关系
                        queryModelMapper.delFilterAndFilterGroup(filterId);
                    }
                }
            }
        }
        //删除filtergroup
        queryModelMapper.delFilterGroup(combinationId);
        //删除queryGroup
        queryModelMapper.delQueryGroup(combinationId);
    }
    /**
     * 修改组合标签
     *
     * @param combinationId
     * @param combinationName
     * @param combinationDes
     * @param scenarious
     * @param departId
     * @param jsonArrays
     */
    @Override
    public void updateCombination(String combinationId, String defaultCode,String combinationName, String combinationDes,
                                  String scenarious, String departId, JSONArray jsonArrays,String defaultName,
                                  String renew,String rule,String manager) {
        updateCombination(combinationId,defaultCode,combinationName,combinationDes,scenarious,departId,jsonArrays,defaultName,
                renew,rule,manager,null);
    }
    /**
     * 修改组合标签
     *
     * @param combinationId
     * @param combinationName
     * @param combinationDes
     * @param scenarious
     * @param departId
     * @param jsonArrays
     */
    @Override
    public void updateCombination(String combinationId,String defaultCode, String combinationName, String combinationDes, String scenarious, String departId, JSONArray jsonArrays,String defaultName,String renew,String rule,String manager,String businessType) {

        //修改组合标签
        Combination combination = new Combination();
        //设置id
        combination.setCombinationId(combinationId);
        combination.setCombinationName(combinationName);
        combination.setBusinessType(businessType);
        combination.setCombinationDes(combinationDes);
        combination.setScenarious(scenarious);
        combination.setDepartId(departId);
        combination.setRenew(renew);
        combination.setRule(rule);
        combination.setManager(manager);
        //创建时间,更新时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        combination.setUptTime(sdf.format(new Date()));
        combinationMapper.updateCombination(combination);

        //删除查询条件
        delQueryModel(combinationId);
        //删除SQL数据
        combinationMapper.delCombinationData(combinationId);
        CombinationGroup defGroup = new CombinationGroup();
        defGroup.setId(IDGenerator.gen());
        defGroup.setCombinationId(combination.getCombinationId());
        defGroup.setGroupNum("0");
        defGroup.setLabitemCode(defaultCode);
        defGroup.setLabitemName(defaultName);
        queryModelMapper.addQueryGroup(defGroup);

        for (int i = 0; i < jsonArrays.size() ; i++) {

            JSONObject jsonObject = jsonArrays.getJSONObject(i);
            //保存查询条件
            QueryModel queryModel = JSON.toJavaObject(jsonObject, QueryModel.class);

            CombinationGroup cgroup = new CombinationGroup();
            cgroup.setId(IDGenerator.gen());
            cgroup.setCombinationId(combination.getCombinationId());
            cgroup.setGroupNum(queryModel.getGroupNum());
            cgroup.setLabitemCode(queryModel.getLabitemCode());
            cgroup.setLabitemName(queryModel.getLabitemName());
            queryModelMapper.addQueryGroup(cgroup);

            if (queryModel.getFilterGroup() == null) {
                throw new CombinationException(ExceptionCodes.COMBINATION_80003);
            }
            //新增条件组
            String parentId = "-";
            setFilterGroup(combination.getCombinationId(),queryModel.getGroupNum(), queryModel.getFilterGroup(), parentId);
        }
        //保存sql数据
        saveCombinationData(combination.getCombinationId());

    }

    @Override
    public void updateCombination(CombinationModel combinationModel) {
        //修改组合标签
        Combination combination = new Combination();
        final JSONArray jsonArrays = JSONObject.parseArray(combinationModel.getQueryCriteria());
        //设置id
        combination.setValidTime(combinationModel.getValidTime());
        combination.setCombinationId(combinationModel.getCombinationId());
        combination.setCombinationName(combinationModel.getCombinationName());
        combination.setCombinationDes(combinationModel.getCombinationDes());
        combination.setBusinessType(combinationModel.getBusinessType());
        combination.setScenarious(combinationModel.getScenarious());
        combination.setDepartId(combinationModel.getDepartId());
        combination.setRenew(combinationModel.getRenew());
        combination.setRule(combinationModel.getRule());
        combination.setManager(combinationModel.getManager());
        //创建时间,更新时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        combination.setUptTime(sdf.format(new Date()));
        combinationMapper.updateCombination(combination);

        //删除查询条件
        delQueryModel(combinationModel.getCombinationId());
        //删除SQL数据
        combinationMapper.delCombinationData(combinationModel.getCombinationId());
        CombinationGroup defGroup = new CombinationGroup();
        defGroup.setId(IDGenerator.gen());
        defGroup.setCombinationId(combination.getCombinationId());
        defGroup.setGroupNum("0");
        defGroup.setLabitemCode(combinationModel.getDefaultCode());
        defGroup.setLabitemName(combinationModel.getDefaultName());
        queryModelMapper.addQueryGroup(defGroup);

        for (int i = 0; i < jsonArrays.size() ; i++) {

            JSONObject jsonObject = jsonArrays.getJSONObject(i);
            //保存查询条件
            QueryModel queryModel = JSON.toJavaObject(jsonObject, QueryModel.class);

            CombinationGroup cgroup = new CombinationGroup();
            cgroup.setId(IDGenerator.gen());
            cgroup.setCombinationId(combination.getCombinationId());
            cgroup.setGroupNum(queryModel.getGroupNum());
            cgroup.setLabitemCode(queryModel.getLabitemCode());
            cgroup.setLabitemName(queryModel.getLabitemName());
            queryModelMapper.addQueryGroup(cgroup);

            if (queryModel.getFilterGroup() == null) {
                throw new CombinationException(ExceptionCodes.COMBINATION_80003);
            }
            //新增条件组
            String parentId = "-";
            setFilterGroup(combination.getCombinationId(),queryModel.getGroupNum(), queryModel.getFilterGroup(), parentId);
        }
        //保存sql数据
        saveCombinationData(combination.getCombinationId());
    }

    /**
     * 查询单个组合标签详细信息
     *
     * @param combinationId
     * @return
     */
    @Override
    public Combination findOneById(String combinationId) {
        //组合标签信息
        Combination combination = combinationMapper.findOneById(combinationId);
        if ("1".equals(combination.getApprovalStatus())) {
            combination.setApprovalStatusName("-");
        }else if ("2".equals(combination.getApprovalStatus())) {
            combination.setApprovalStatusName("待审核");
        } else if ("3".equals(combination.getApprovalStatus())) {
            combination.setApprovalStatusName("驳回");
        } else if ("4".equals(combination.getApprovalStatus())) {
            combination.setApprovalStatusName("已通过");
        }

        //查询帅选结果
        List<CombinationGroup> cgroupList = queryModelMapper.findListQueryGroup(combinationId);
        combination.setCgrouplist(cgroupList);

        //查询filter列表
        List<Filter> filters = new ArrayList<>();
        List<FilterGroup> filterGroups = findFilterGroup("-", combinationId, filters);

        List<QueryModel> newList = new ArrayList<>();
        for (FilterGroup filterGroup : filterGroups) {
            QueryModel newModel = new QueryModel();
            Map<String, String> cgMap = new HashMap<>();
            cgMap.put("combinationId", combinationId);
            cgMap.put("groupNum", filterGroup.getGroupNum());
            CombinationGroup dbGroup = queryModelMapper.findByIdNum(cgMap);
            newModel.setGroupNum(filterGroup.getGroupNum());
            newModel.setLabitemCode(dbGroup.getLabitemCode());
            newModel.setLabitemName(dbGroup.getLabitemName());
            newModel.setFilterGroup(filterGroup);
            newList.add(newModel);
        }
        newList = newList.stream().sorted(Comparator.comparing(QueryModel::getGroupNum)).collect(Collectors.toList());
        combination.setQueryModelList(newList);

        //查询列表
        if (filters != null && !filters.isEmpty()) {
            Map<String, String> filtermap;
            for (Filter filter : filters) {
                filtermap = new HashMap<>();
                if (filter.getValueList() != null && !filter.getValueList().isEmpty()) {
                    String valueName = "";
                    for (String value : filter.getValueList()) {
                        Map<String, String> map = new HashMap<>();
                        map.put("dim_id", filter.getDimId());
                        map.put("item_no", value);
                        valueName = queryModelMapper.findValueName(map);
                        filtermap.put(value, valueName);
                    }
                }
                filter.setValueName(filtermap);
            }
            combination.setFilterList(filters);
        }
        return combination;
    }


    @Override
    //查询条件组
    public List<FilterGroup> findFilterGroup(String parentId, String combinationId, List<Filter> filters) {
        Map<String, String> fgmap = new HashMap<>();
        fgmap.put("parentId", parentId);
        fgmap.put("combinationId", combinationId);
        List<FilterGroup> filterGroupList = queryModelMapper.findFilterGroup(fgmap);

        Filter filter;
        List<Filter> filterList;
        if (filterGroupList != null && !filterGroupList.isEmpty()) {
            for (FilterGroup filterGroup : filterGroupList) {
                filterList = new ArrayList<>();
                //查找条件
                List<String> filterIds = queryModelMapper.findFilterIds(filterGroup.getId());
                if (filterIds != null && !filterIds.isEmpty()) {
                    for (String filterId : filterIds) {
                        filter = new Filter();
                        filter = queryModelMapper.findOneFilterById(filterId);
                        filter.setCnDateName(fetchCNDateName(filter));
                        filter.setValueList(JSON.parseArray(filter.getValueListStr(), String.class));
                        filterList.add(filter);
                        filters.add(filter);
                    }
                }
                filterGroup.setFilters(filterList);

                List<FilterGroup> list = findFilterGroup(filterGroup.getId(), combinationId, filters);
                if (list != null && !list.isEmpty()) {
                    filterGroup.setChildren(list);
                }else{
                    filterGroup.setChildren(new ArrayList<FilterGroup>());
                }
            }
        }
        return filterGroupList;
    }


    private final static String CN_DATE_FORMAT = "当前月份%s";
    private static final String MONTH_FORMAT = "%s年%s月";
    private static final String zero = "0";

    private String fetchCNDateName(Filter filter) {
        if ("true".equals(filter.getTimeType())) {
            return zero.equals(filter.getDataDate()) ? String.format(CN_DATE_FORMAT, "") : String.format(CN_DATE_FORMAT, "-" + filter.getDataDate());
        } else {
            String year = StringUtils.substring(filter.getDataDate(), 0, 4);
            String month = StringUtils.substring(filter.getDataDate(), 4);
            return month.startsWith(zero) ? String.format(MONTH_FORMAT, year, month.substring(1)) : String.format(MONTH_FORMAT, year, month);
        }
    }



    private static String format(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.format(date);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public void addDimData(String combinationId) {
            Combination combination = combinationMapper.findOneById(combinationId);
            DimData dimData = new DimData();
            dimData.setDimId(combinationId);
            dimData.setValidTime(combination.getValidTime());
            dimData.setBusinessType(combination.getBusinessType());
            dimData.setDimName(combination.getCombinationName());
            dimData.setDefinition(combination.getCombinationDes());
            dimData.setDimLargeType(DimCofig.GROUP_DIM);//标签分类-组合标签
            dimData.setClassify("02");//标志型
            DimCatalog catalog = queryModelMapper.findByCatalogName(TagConstants.PRIVATE_CATALOGID);
            dimData.setCatalogId(catalog.getId());//目录
            dimData.setCatalogName(TagConstants.PRIVATE_CATALOGID);
            dimData.setState("01");//启用
            dimData.setIsrecommended(false);
            dimData.setIscollect(false);
            dimData.setCreaterId(combination.getOwnerId());
            dimData.setBusinessLeader(combination.getManager());
            dimData.setBusinessDepartment(combination.getDepartId());
            dimData.setApprover(combination.getApprover());
            dimData.setDepartment(combination.getDepartId());
            dimData.setScenarios(combination.getScenarious());
            dimData.setUpdataCycle(combination.getRenew());
            String date = DateHelper.currentDateTime();
            dimData.setCreateTime(date);
            dimData.setUptTime(combination.getUptTime());
            dimData.setApproveDate(date);
            dimData.setColName(combination.getColName());
            dimData.setSortNum(combination.getSortNum());
            dimData.setCaliber(combination.getRule());
            dimMapper.addFromCombination(dimData);

            List<CombinationGroup> groupList = queryModelMapper.findListQueryGroup(combinationId);

            if (CollectionUtils.isNotEmpty(groupList)) {

                for (CombinationGroup group : groupList) {
                    DimItem item = new DimItem();
                    item.setId(IdWorker.nextId());
                    item.setDimId(combinationId);
                    item.setUpdateDate(date);
                    item.setItemNo(group.getLabitemCode());
                    item.setItemName(group.getLabitemName());
                    dimItemMapper.addsFormCombination(item);
                }
            }
    }



    @Override
    public void saveCombinationData(String combinationId) {

        Combination combination = combinationMapper.findOneById(combinationId);
        CombinationData cData = new CombinationData();
        cData.setCombinationId(combinationId);
        cData.setCombinationName(combination.getCombinationName());
        cData.setCombinationDes(combination.getCombinationDes());
        cData.setScenarious(combination.getScenarious());
        cData.setColName(combination.getColName());
        cData.setDepartId(combination.getDepartId());
        String date = DateHelper.currentDateTime();
        cData.setCreateTime(date);
        cData.setUptTime(date);
        cData.setSourceField(sourceField(combinationId));//设置源字段

        List<Filter> filters = new ArrayList<>();
        List<FilterGroup> fgList = findFilterGroup("-", combinationId, filters);

        if (!CollectionUtils.isEmpty(fgList)){
            if (fgList.size() == 1){ //父组为1 说明是单组
                cData.setGroupType("0");
                cData.setScreenRule(singleGroup(fgList));
            }else{
                //大于1说明多组
                cData.setGroupType("1");
                cData.setScreenRule(moreGroup(fgList,combinationId));
            }
        }
        combinationMapper.addCombinationData(cData);
    }

    @Override
    public void delCombinationData(String combinationId) {
        combinationMapper.delCombinationData(combinationId);
    }

    //获取源字段
    protected String sourceField(String combinationId){
        List<Filter> filterList = queryModelMapper.findFilterById(combinationId);
        String sourceField = "";
        StringBuffer buffer = new StringBuffer(sourceField);
        if (!CollectionUtils.isEmpty(filterList)){
            for (int i = 0; i < filterList.size(); i++) {
                if (i == (filterList.size()-1)){
                    buffer.append(getRealDim(filterList.get(i).getColName(),filterList.get(i).getDataDate()));
                }else{
                    buffer.append(getRealDim(filterList.get(i).getColName(),filterList.get(i).getDataDate()));
                    buffer.append(",");
                }
            }
        }
        return buffer.toString();
    }

    public String hander(FilterGroup filterGroup){

        StringBuffer buffer = new StringBuffer();
        if (filterGroup != null) {
            if (!CollectionUtils.isEmpty(filterGroup.getFilters())) {
                for (int i = 0; i < filterGroup.getFilters().size(); i++) {
                    if (i == (filterGroup.getFilters().size() - 1)) {
                        buffer.append(" ( ");
                        buffer.append(getValue(filterGroup.getFilters().get(i)));
                        buffer.append(" ) ");
                    } else {
                        buffer.append(" ( ");
                        buffer.append(getValue(filterGroup.getFilters().get(i)));
                        buffer.append(" ) ");
                        buffer.append(filterGroup.getSymbol());
                    }
                }
            }
            if (!CollectionUtils.isEmpty(filterGroup.getChildren())) {
                if (!org.springframework.util.CollectionUtils.isEmpty(filterGroup.getFilters())){
                    buffer.append(filterGroup.getSymbol());
                }
                for (int i = 0; i < filterGroup.getChildren().size(); i++) {
                    if (i == filterGroup.getChildren().size()-1){
                        buffer.append(" ( ");
                        buffer.append(hander(filterGroup.getChildren().get(i)));
                        buffer.append(" ) ");
                    }else{
                        buffer.append(" ( ");
                        buffer.append(hander(filterGroup.getChildren().get(i)));
                        buffer.append(" ) ");
                        buffer.append(filterGroup.getSymbol());
                    }

                }
            }
        }
        return buffer.toString();
    }

    private String getValue(Filter filter){

        StringBuffer buffer = new StringBuffer();
        List<String> valueList  = JSON.parseArray(filter.getValueListStr(), String.class);
        String classify = filter.getClassify();//标签类型
        String type = filter.getType();
        buffer.append(getRealDim(filter.getDimId(),filter.getDataDate())+" ");

        if ("equal".equals(type)){
            if ("02".equals(classify) || "05".equals(classify)) {//标志型
                buffer.append(" = ").append("'").append(valueList.get(0)).append("' ");
            }else if ("03".equals(classify)){//指标型
                buffer.append(" = ").append(valueList.get(0)).append(" ");
            }
        }else if ("no_equal".equals(type) ){
            if ("02".equals(classify) || "05".equals(classify)){
                buffer.append(" != ").append("'").append(valueList.get(0)).append("' ");
            }else if ("03".equals(classify)){//指标型
                buffer.append(" != ").append(valueList.get(0)).append(" ").append(" or ")
                        .append(getRealDim(filter.getColName(),filter.getDataDate())).append(" is null");
            }
        }else if ("contain".equals(type)){
            if ("02".equals(classify)){
                buffer.append(" in (").append(value(valueList)).append(") ");
            }else if ("01".equals(classify)){
                buffer.append(" like '%").append(valueList.get(0)).append("%' ");
            }
        }else if ("contain_everything".equals(type)){
            if ("06".equals(classify)){
                int i = 0;
                String name = buffer.toString();
                for (String value:valueList){
                    if(i==0){
                        i++;
                        buffer.append(" like '%").append(value).append("%' ");
                        continue;
                    }
                    buffer.append(" or ").append(name).append(" like '%").append(value).append("%' ");
                }
            }
        }else if ("not_contain".equals(type)){
            if ("02".equals(classify)){
                buffer.append(" not in (").append(value(valueList)).append(") ");
            }else if ("01".equals(classify)){
                buffer.append(" not like '%").append(valueList.get(0)).append("%' ");
            }
        }else if ("greater".equals(type)){
            if ("03".equals(classify)){
                buffer.append(" > ").append(valueList.get(0)).append(" ");
            }else if ("05".equals(classify)){
                buffer.append(" > '").append(valueList.get(0)).append("' ");
            }
        }else if ("less".equals(type)){
            if ("03".equals(classify)){
                buffer.append(" < ").append(valueList.get(0)).append(" ");
            }else if ("05".equals(classify)){
                buffer.append(" < '").append(valueList.get(0)).append("' ");
            }
        }else if ("greater_equal".equals(type)){
            if ("03".equals(classify)){
                buffer.append(" >= ").append(valueList.get(0)).append(" ");
            }else if ("05".equals(classify)){
                buffer.append(" >= '").append(valueList.get(0)).append("' ");
            }
        }else if ("less_equal".equals(type)){
            if ("03".equals(classify)){
                buffer.append(" <= ").append(valueList.get(0)).append(" ");
            }else if ("05".equals(classify)){
                buffer.append(" <= '").append(valueList.get(0)).append("' ");
            }
        }else if ("among".equals(type)){
            if ("03".equals(classify)){
                buffer.append(" between ").append(valueList.get(0)).append(" and ").append(valueList.get(1)).append(" ");
            }else if ("05".equals(classify)){
                buffer.append(" between '").append(valueList.get(0)).append("' and '").append(valueList.get(1)).append("' ");
            }
        }else if ("not_among".equals(type)){
            if ("03".equals(classify)){
                buffer.append(" not between ").append(valueList.get(0)).append(" and ").append(valueList.get(1)).append(" or ")
                .append(getRealDim(filter.getColName(),filter.getDataDate())).append(" is null");
            }else if ("05".equals(classify)){
                buffer.append(" not between '").append(valueList.get(0)).append("' and '").append(valueList.get(1)).append("' ");
            }
        }
        return buffer.toString();
    }

    private String getRealDim(String dimId,String dataDate){

        if (FieldHandler.ZERO.equals(dataDate) || (FieldHandler.pattern.matcher(dataDate)).matches() && dataDate.length() == FieldHandler.LENGTH8){
            return dimId+"_${currentMonth}";
        }else{
            Map<String, String> relation = esInfoService.symbolRelation("1");
            String symbol = Optional.ofNullable(relation.get(dataDate)).orElse(dataDate);
            return dimId+"_${"+symbol+"}";
        }
    }

    private String value(List<String> valus){
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < valus.size(); i++) {
            if (i==valus.size()-1){
                buffer.append("'").append(valus.get(i)).append("'");
            }else{
                buffer.append("'").append(valus.get(i)).append("',");
            }
        }
        return buffer.toString();
    }

    /**
     * 单组拼接筛选条件SQL
     * @param fgList
     * @return
     */
    private String singleGroup(List<FilterGroup> fgList){
        StringBuffer buffer = new StringBuffer();
        buffer.append(" case when ");
        buffer.append(hander(fgList.get(0)));
        buffer.append(" then 1 else 0 end as tag_value ");
        return buffer.toString();
    }

    /**
     * 多组拼接筛选条件SQL
     * @param fgList
     * @return
     */
    private String moreGroup(List<FilterGroup> fgList,String combinationId){

        Map<String ,String > map = new HashMap<>();
        map.put("combinationId",combinationId);
        StringBuffer buffer = new StringBuffer();
        buffer.append("case ");
        for (int i = 0; i < fgList.size(); i++) {
            buffer.append(" when ");
            buffer.append(hander(fgList.get(i)));
            buffer.append(" then '");
            map.put("groupNum",fgList.get(i).getGroupNum());
            buffer.append(queryModelMapper.findByIdNum(map).getLabitemCode()+"' ");
        }
        buffer.append(" else '");
        map.put("groupNum","0");
        buffer.append(queryModelMapper.findByIdNum(map).getLabitemCode()+"' ");
        buffer.append(" end as tag_value ");
        return buffer.toString();

    }

}
